﻿using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.Controls;
using Microsoft.UI.Xaml.Navigation;

namespace DimensionsHelper.Client.WinUi.Views;

public sealed partial class TableFormatterPage : ItemsPageBase
{
    public TableFormatterPage()
    {
        ViewModel = App.GetService<TableFormatterViewModel>();
        InitializeComponent();
        JsonPathSettingsCard.Loaded += OnJsonPathSettingsCardLoaded;
    }

    public TableFormatterViewModel ViewModel
    {
        get;
    }


    private static void OnJsonPathSettingsCardLoaded(object sender, RoutedEventArgs e)
    {
        SettingsCard card = (SettingsCard)sender;

        Grid? root = card.FindDescendant("PART_RootGrid") as Grid;
        if (root == null)
        {
            return;
        }

        VisualStateGroup? group = VisualStateManager.GetVisualStateGroups(root)
            .FirstOrDefault(g => g.Name == "ContentAlignmentStates");
        VisualState? state = group?.States.FirstOrDefault(s => s.Name == "Left");

        if (state?.Setters.FirstOrDefault(s => s is Setter obj && obj.Target.Path.Path == "HorizontalAlignment") is
            Setter hAlign)
        {
            hAlign.Value = HorizontalAlignment.Stretch;
        }

        card.ContentAlignment = ContentAlignment.Left;
    }


    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        Items = PageInfoDataSource.Instance.GetPageInfosOfType(typeof(TableFormatterViewModel));
    }
}